package com.cnlxu.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * Created by cnlxu on 2016/8/9.
 */
public class TileLayout extends LinearLayout{
    private boolean isPressed;
    private ScaleAnimation zoomInAnimation;
    private ScaleAnimation zoomOutAnimation;

    public TileLayout(Context context) {
        super(context);
    }

    public TileLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TileLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasure){
        super.onMeasure(widthMeasureSpec, heightMeasure);
    }
    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
    }

    private void toNormalState(){
        isPressed = false;
        invalidate();
        startAnimation(zoomOutAnimation);
    }

    private boolean pointInView(float lx,float ly, float slop){
        return (lx >= -slop
                && ly >= -slop
                && lx < getWidth() + slop
                && ly < getHeight() +slop);
    }

    private void init(){
        zoomInAnimation = new ScaleAnimation(1f, 0.95f, 1f, 0.95f);
        zoomInAnimation.setFillAfter(true);
        zoomInAnimation.setDuration(200);

        zoomOutAnimation = new ScaleAnimation(0.95f, 1f, 0.95f, 1f);
        zoomOutAnimation.setFillAfter(true);
        zoomOutAnimation.setDuration(200);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isPressed = true;//设置true
                invalidate();//重绘
                this.startAnimation(zoomInAnimation);//执行动画
                break;
            case MotionEvent.ACTION_UP:
                boolean needPerformClick = isPressed;
                toNormalState();//正常
                if (needPerformClick) {
                    performClick();
                }
                break;

            case MotionEvent.ACTION_MOVE:
                final int x = (int) event.getX();
                final int y = (int) event.getY();
                if (!pointInView(x, y, 20)) {
                    toNormalState();
                }
                break;

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                toNormalState();
                break;
        }

        return true;
    }



}
